/**
 * Created by CZ on 2017/4/6.
 */
module.exports = function ($scope,$interval,$state,$rootScope,RequestService,modelService,$localStorage,commonConfig,$http) {
    $scope.User = $localStorage.get('cloud');
    if($scope.User){
        //////////////----------------------------------------------以下为普通形式（TODO 盐城）----------------------------------------------------------//////////////
        if($scope.User.detail){
            if(commonConfig.version === 'noAdvertising'){  // 无广告版本需要判断LS用户信息是否过期
                //判断保存时间有无过期
                var currentTime = new Date();
                //若过期则删除
                if(currentTime > $localStorage.get('cloud').deadline){
                    console.log('login———>保存时间过期');
                    $localStorage.remove('cloud');
                    codeLogin();
                }else {
                    goToHomepage();
                }
            }else {
                goToHomepage()
            }
        }else {
            codeLogin()
        }
    }else {
        codeLogin()
    }
    function codeLogin(){
        //////////////----------------------------------------------以下为单点形式跳转----------------------------------------------------------//////////////
        console.log($localStorage.get('cloud-url'));
        var url = encodeURIComponent($localStorage.get('cloud-url')?$localStorage.get('cloud-url'):commonConfig.cloudHomepage+'login');
        //删除保存的域名
        $localStorage.remove('cloud-url');
        var queryString = function(key){
            return (document.location.search.match(new RegExp("(?:^\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1];
        };
        var code = queryString('code');
        if(!code){  //若第一退出直接再登录没有code
            var url = commonConfig.cloudHomepage+'login';
            //跳转到用户首页
            $localStorage.set('cloud-url',url); //保存跳转后的域名，以便验证code
            RequestService.getCode(encodeURIComponent(url));
        }else {
            //获取登录的access_token
            RequestService.getLoginAccessToken(code,url).then(function(response){
                console.log(response);
                getUser(response.data.access_token);
            },function(error){
                console.log(error);
            });
            function getUser(token){   //获取用户单点信息
                RequestService.getUser(token).then(function(response){
                    console.log(response);
                    var deadline = new Date(new Date(new Date().toLocaleDateString().replace(/年|月|日/g,  "/")).getTime()+24*60*60*1000-1).getTime();
                    $scope.User = {
                        username:response.data.name,
                        authority:response.data.authorities[0].authority,
                        token:response.data.details.tokenValue,
                        detail:null,
                        deadline:deadline,
                        isCommonFun:false
                    };
                    // $rootScope.token = response.data.details.tokenValue;
                    $localStorage.set('cloud',$scope.User);
                    getUserDetails();  //获取用户详细信息
                },function(error){
                    console.log(error);
                });
            }
            function getUserDetails(){ //获取用户详细信息
                // console.log($scope.User);
                $http.get(commonConfig.$webroot+commonConfig.userApi+'user/user/getUserByUserName?userName='+$scope.User.username+'&access_token=' + $scope.User.token).then(function successCallback(response) {
                    console.log(response);
                    $scope.User.detail = response.data;
                    $localStorage.set('cloud',$scope.User);
                    goToHomepage()
                }, function errorCallback(error) {
                    console.log(error);
                });
            }
        }
    }
    //根据用户类型跳转相应首页
    function goToHomepage(){
        switch($scope.User.authority){
            case 'CloudAdmin':
                window.location.href = commonConfig.cloudAdminHomepage;
                break; //平台管理员首页
            case 'Developer':
                window.location.href = commonConfig.developerHomepage;
                break; //开发者首页
            //TODO：二职修改
            case 'Student':
                if(commonConfig.version === 'second'){
                    window.location.href = commonConfig.stuHomepage;
                }else {
                    $state.go('CloudUser.AppMain');
                }
                break;
            //TODO：二职修改
            // case 'Teacher':
            //     window.location.href = commonConfig.stuHomepage;
            //     break; //教师首页
            default:
                $state.go('CloudUser.AppMain');
                break;
        }
    }
};